<?php

class Conexao{
	private static $instancia;
	private static $servidor="localhost";
	private static $usuario="root";
	private static $senha="";
	private static $banco="cemet";
	
	
	private function __construct(){
	}
	
	public static function getConexao(){
		if(!isset(self::$instancia)){
			$con = __CLASS__;
			self::$instancia = new $con;
		}
		return self::$instancia;
	}
	
	
	public static function executaSql($sql){
		print_r($sql);
		$mysqli = new mysqli(self::$servidor, self::$usuario, self::$senha, self::$banco);
		$query  = $sql;
		/* execute multi query */
		if ($mysqli->multi_query($query)) {
		do {
	    	    /* store first result set */
    	    	if ($result = $mysqli->store_result()) {
            		while ($row = $result->fetch_row()) {
                		printf("%s\n", $row[0]);
            		}
            		$result->free();
        		}
        		/* print divider */
        		if ($mysqli->more_results()) {
            	printf("-----------------\n");
        		}
    		} while ($mysqli->next_result());
		}else{
	
			$con = mysql_connect(self::$servidor, self::$usuario, self::$senha);
			$bd = mysql_select_db(self::$banco);
			mysql_query($query);	
		}
		$mysqli->close();		
			
	}
	
	
	public static function tabelaSql($sql){
		$tabAux = array();
		$conn=mysql_connect(self::$servidor,self::$usuario,self::$senha);
		$bd=mysql_select_db(self::$banco);
		$tabela = mysql_query($sql) or die("Erro ao ler tabela!");
	
		
		while ($linha = mysql_fetch_assoc($tabela)){
			if(isset($linha)){
				array_push($tabAux, $linha);
			}
		}

		return $tabAux;
	}
	
	public static function imprimePlanilha($sql, $nomeDoArquivo){
		$conn=mysql_connect(self::$servidor,self::$usuario,self::$senha);
		$bd=mysql_select_db(self::$banco);
	
		$arquivo = $nomeDoArquivo.".xls";
			
		$html = "<table>";
			
			
		$html .= "<tr>";
		$tab = mysql_query($sql);
		$colunas = mysql_num_fields($tab);
			
		for($i=0; $i<$colunas; $i++){
			$cabecalho = mysql_field_name($tab, $i);
			$html.="<th>".$cabecalho."</th>";
		}
	
		$html .= "</tr>";
			
		while ($linha = mysql_fetch_array($tab)){
			$html .= "<tr>";
			for ($i=0; $i<$colunas; $i++){
				$html .="<td>".str_replace(".",",",$linha[$i])."</td>";
			}
			$html .="</tr>";
		}
	
		$html .= "</table>";
			
		// Configura��es header para for�ar o download
		header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header ("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
		header ("Cache-Control: no-cache, must-revalidate");
		header ("Pragma: no-cache");
		header ("Content-type: application/x-msexcel");
		header ("Content-Disposition: attachment; filename=\"{$arquivo}\"" );
		header ("Content-Description: PHP Generated Data" );
			
		// Envia o conte�do do arquivo
		return $html;
		exit;	
	}
	
}
?>